#include "cJSON.h"
#include <stdio.h>

int main(int argc, char const *argv[])
{
    // 1.将字符串转换为JSON对象，提取其中的值
    // 2.随便生成一个JSON字符串
    char *json = "{\"name\":\"zhangsan\",\"age\":18,\"sex\":\"man\"}";
    // 先转成cjson结构体，然后再提取对应元素cjosn 元素json提取值
    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        printf("json parse error\n");
        return -1;
    }
    // 2.提取元素
    cJSON *name_cjson = cJSON_GetObjectItem(root, "name");
    cJSON *age_cjson = cJSON_GetObjectItem(root, "age");
    char *name = name_cjson->valuestring;
    int age = age_cjson->valueint;
    printf("name:%s, age:%d\n", name, age);

    // 3.把值组合成一个新的json
    cJSON *new_root = cJSON_CreateObject();
    cJSON_AddStringToObject(new_root, "name", "lisi");
    cJSON_AddNumberToObject(new_root, "age", 20);

    // 4.打印无格式化的json
    char *new_json = cJSON_PrintUnformatted(new_root);
    printf("new_json:%s\n", new_json);

    // 5.释放内存
    cJSON_Delete(root);
    cJSON_Delete(new_root);

    return 0;
}
